<?php
/**
 * Created by PhpStorm.
 * Author: wenwenbin
 * Date: 2017/12/22
 * Time: 11:21
 */
namespace App\Http\Admin\Personnel\Models;

use App\Api\Job\Resume\Models\Resume;
use App\Eloquent\Oa\CompanyUser;
use App\Eloquent\Oa\Contacts;
use App\Eloquent\Oa\Department;
use App\Eloquent\Oa\EmployeeNumber;
use App\Eloquent\Oa\PersonnelFile;
use App\Eloquent\Oa\TemporaryWorker;
use App\Eloquent\Oa\WorkHistory;
use App\Eloquent\App\User;
use App\Eloquent\Role;
use App\Eloquent\UserRole;
use App\Repositories\Metadata\CityRepository;
use App\Repositories\OA\CompanyResumeRepository;
use App\Repositories\OA\CompanyUserRepository;
use Framework\BaseClass\Http\Admin\Model;

class AddressList extends Model
{

    /**
     * 获取员工列表数据
     * @author wenwenbin
     * @param int $company_id 公司id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getEmployeeList($company_id)
    {
        $departmentList = Department::where([['oa_company_id', $company_id], ['pid', 0]])
            ->with(['contactsList' => function ($query) {
                $query->select('id', 'oa_department_id', 'name', 'mobile', 'position', 'email');
            }, 'subordinateList'])
            ->get(['id', 'name']);
        foreach ($departmentList as $k => $department) {
            foreach ($department->subordinateList as $v => $item) {
                $department->contactsList[] = $this->getDepartmentEmployeeList($item->id);
            }
            unset($department->id, $department->subordinateList);
        }

        return ['list' => $departmentList, 'pageSize' => 10000];
    }

    /**
     * 通过递归获取下级部门和员工信息
     * @author wenwenbin
     * @param $departmentId
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|mixed|null|static|static[]
     */
    private function getDepartmentEmployeeList($departmentId)
    {
        $department = Department::with(['contactsList' => function ($query) {
            $query->select('id', 'oa_department_id', 'name', 'mobile', 'position', 'email');
        }, 'subordinateList'])->find($departmentId, ['id', 'name']);
        if (is_null($department)) xThrow(ERR_OA_DEPARTMENT_NOT_EXIST);
        foreach ($department->subordinateList as $k => $item) {
            $department->contactsList[] = $this->getDepartmentEmployeeList($item->id);
        }
        unset($department->id, $department->subordinateList);

        return $department;
    }

    /**
     * 获取员工信息
     * @author wenwenbin
     * @param int $id 员工id
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function getEmployeeInfo($id)
    {
        $employee = Contacts::with('employeeNumberInfo', 'userInfo.userRoleList.roleInfo')->find($id);
        if (is_null($employee)) xThrow(ERR_OA_CONTACTS_NOT_EXIST);
        if (is_null($employee->userInfo)) xThrow(ERR_CLIENT_USER_NOT_EXIST);
        if ($employee->userInfo->userRoleList->isNotEmpty()) {
            if (is_null($employee->userInfo->userRoleList[0]->roleInfo)) {
                $role_id = '';
            } else {
                $role_id = $employee->userInfo->userRoleList[0]->roleInfo->id;
            }
        } else {
            $role_id = '';
        }
        if ($employee->type == 1) {
            $employeeInfo = PersonnelFile::where([['oa_company_id', $employee->oa_company_id], ['oa_contacts_id', $employee->id]])->first();
            if (is_null($employeeInfo)) xThrow(ERR_OA_PERSONNEL_FILE_NOT_EXIST, '该员工尚未入职');
            $employeeInfo->type = $employee->type;
            $employeeInfo->oa_department_id = $employee->oa_department_id;
            $employeeInfo->profile_photo_url = $employee->profile_photo_url;
            $employeeInfo->mobile = $employee->mobile;
            $employeeInfo->birthdate = date('Y-m-d', $employeeInfo->birthdate);
            if ($employeeInfo->accumulation_fund_adjust_time) {
                $employeeInfo->accumulation_fund_adjust_time = date('Y-m-d', $employeeInfo->accumulation_fund_adjust_time);
            } else {
                $employeeInfo->accumulation_fund_adjust_time = '';
            }
            if ($employeeInfo->insured_adjust_time) {
                $employeeInfo->insured_adjust_time = date('Y-m-d', $employeeInfo->insured_adjust_time);
            } else {
                $employeeInfo->insured_adjust_time = '';
            }
            if ($employeeInfo->health_certificate_term) {
                $employeeInfo->health_certificate_term = date('Y-m-d', $employeeInfo->health_certificate_term);
            } else {
                $employeeInfo->health_certificate_term = '';
            }
            $employeeInfo->id = $employee->id;
            $employeeInfo->employee_number = $employee->employeeNumberInfo->id;
            $employeeInfo->role_id = $role_id;
            return $employeeInfo;
        } elseif ($employee->type == 2) {
            $employeeInfo = TemporaryWorker::where([['oa_company_id', $employee->oa_company_id], ['oa_contacts_id', $employee->id]])->first();
            if (is_null($employeeInfo)) xThrow(ERR_OA_TEMPORARY_WORKER_NOT_EXIST);
            $employeeInfo->start_time = $employeeInfo->start_time ? date('Y-m-d', $employeeInfo->start_time) : '';
            $employeeInfo->type = $employee->type;
            $employeeInfo->oa_department_id = $employee->oa_department_id;
            $employeeInfo->profile_photo_url = $employee->profile_photo_url;
            $employeeInfo->mobile = $employee->mobile;
            $employeeInfo->birthdate = date('Y-m-d', $employeeInfo->birthdate);
            $employeeInfo->id = $employee->id;
            $employeeInfo->employee_number = $employee->employeeNumberInfo->id;
            $employeeInfo->role_id = $role_id;
            return $employeeInfo;
        } else {
            xThrow(ERR_OPTION_NOT_EXIST_IN_DATABASE);
        }
    }

    /**
     * 获取编辑员工信息页面的部门列表数据
     * @author wenwenbin
     * @param int $company_id 公司id
     * @return \Illuminate\Support\Collection
     */
    public function getDepartmentList($company_id)
    {
        return Department::where('oa_company_id', $company_id)->get();
    }

    /**
     * 获取工号列表
     * @author wenwenbin
     * @param int $company_id 公司id
     * @param null|int $employee_id 员工id
     * @return \Illuminate\Support\Collection
     */
    public function getEmployeeNumberList($company_id, $employee_id = null)
    {
        $temp = EmployeeNumber::where([['oa_company_id', $company_id], ['oa_contacts_id', 0]]);
        if ($employee_id) $temp = $temp->orWhere([['oa_company_id', $company_id], ['oa_contacts_id', $employee_id]]);
        return $temp->get(['id', 'employee_number']);
    }

    /**
     * 保存员工信息
     * @author wenwenbin
     * @param int $id 通讯录id
     * @param int $company_id 公司id
     * @param int $department_id 部门id
     * @param string $position 职位
     * @param string $name 姓名
     * @param int $sex 性别
     * @param int $role_id 角色id
     * @param string $ethnicity 民族
     * @param string $birthplace 籍贯
     * @param int $education 学历
     * @param string $birthdate 出生日期
     * @param int $credential_type 证件类型
     * @param string $credential_number 证件号码
     * @param int $mobile 手机号
     * @param string $email 电子邮箱
     * @param string $address 家庭住址
     * @param int $marital_status 婚姻状况
     * @param int $household_registratio_type 户籍类型
     * @param string $personnel_sources 人员来源
     * @param string $health_certificate_term 健康证有效期
     * @param string $profile_photo_url 通讯录头像
     * @param string $note 备注
     * @param int $type 人员类型
     * @param string $start_time 到厂日期
     * @param string $employee_number 工号
     * @param string $accumulation_fund 公积金
     * @param string $accumulation_fund_base 公积金基数
     * @param string $accumulation_fund_adjust_time 公积金调整时间
     * @param string $social_security_base 社保基数
     * @param string $insured_adjust_time 参保基数调整时间
     * @return bool
     */
    public function saveAddressListMember(
        $id, $company_id, $department_id, $position, $name, $sex, $role_id, $ethnicity,
        $birthplace, $education, $birthdate, $credential_type, $credential_number, $mobile, $email, $address,
        $marital_status, $household_registratio_type, $personnel_sources, $health_certificate_term, $profile_photo_url,
        $note, $type, $start_time, $employee_number, $accumulation_fund, $accumulation_fund_base,
        $accumulation_fund_adjust_time, $social_security_base, $insured_adjust_time)
    {
        \DB::beginTransaction();
        $result = true;
        if ($id) {
            $employee = Contacts::find($id);
            if (is_null($employee)) xThrow(ERR_OA_CONTACTS_NOT_EXIST);
        } else {
            $employee = Contacts::firstOrNew(['mobile' => $mobile, 'oa_company_id' => $company_id]);
            if ($employee->id) xThrow(ERR_OA_CONTACTS_ALREADY_EXIST);
        }
        $employee->fill([
            'oa_department_id'  => $department_id,
            'name'              => $name,
            'mobile'            => $mobile,
            'position'          => $position,
            'email'             => $email ?: '',
            'profile_photo_url' => $profile_photo_url ?: '/images/global/default_avatar.png'
        ]);
        if ($type) $employee->type = $type;

        //查找user表里的用户是否存在，如果不存在，先创建用户，再将user_id添加到通讯录表里
        $user = User::firstOrNew(['customer_name' => $mobile]);
        if (is_null($user->customer_id)) {
            $user->fill([
                'customer_mobile'       => $mobile,
                'customer_pass'         => '123456',
                'customer_zhuceshijian' => time(),
                'customer_avatar'       => $profile_photo_url ?: '/images/global/default_avatar.png'
//                'username' => $mobile,
//                'nickname' => substr_replace($mobile, '****', 3, 4),
//                'name' => $name,
//                'password' => '123456',
//                'profile_photo_url' => $profile_photo_url ?: '/images/global/default_avatar.png',
//                'credential_type' => $credential_type,
//                'credential_number' => $credential_number,
//                'sex' => $sex,
//                'birthdate' => $birthdate ? strtotime($birthdate) : 0,
//                'email' => $email ?: '',
//                'register_ip' => 0, //todo
//                'status' => 10
            ]);
            $result = $user->save() && $result;
        }

        //绑定公司用户
        if (!$id) {
            $number = Contacts::where('oa_company_id', $company_id)->count();
            $companyUser = new CompanyUserRepository();
            $otherCompanyUserIsUse = $companyUser->find([['user_id', $user->customer_id], ['is_use', 1]]);
            $companyUser->create([
                'oa_company_id'    => $company_id,
                'oa_department_id' => $department_id,
                'position'         => $position,
                'role_id'          => $role_id,
                'user_id'          => $user->customer_id,
                'is_use'           => is_null($otherCompanyUserIsUse) ? 1 : 0,
                'type'             => $number ? 0 : 1
            ]);
            if (is_null($otherCompanyUserIsUse)) {
                //如果是公司第一人，直接入职
                if ($number == 0) {
                    $defaultRoleId = $role_id;
                } else {
                    //赋予app默认公司角色
                    $defaultRoleId = Role::where([['oa_company_id', 0], ['name', 'default_company_employee']])->value('id');
                    if (is_null($defaultRoleId)) xThrow(ERR_APP_ROLE_NOT_EXIST);
                }
                $userRole = UserRole::firstOrNew(['user_id' => $user->customer_id]);
                $userRole->role_id = $defaultRoleId;
                $result = $userRole->save() && $result;
            }
        } else {
            $companyUser = new CompanyUserRepository();
            $companyUser->update(
                [
                    'oa_company_id' => $company_id,
                    'user_id'       => $user->customer_id
                ],
                [
                    'oa_department_id' => $department_id,
                    'position'         => $position,
                    'role_id'          => $role_id
                ]
            );
        }

        //绑定通讯录
        $employee->user_id = $user->customer_id;
        $result = $employee->save() && $result;

        //查找该联系人是否已占有工号，如果有，先让该工号的联系人清除，再将该联系人和选择的工号绑定
        $oldEmployeeNumber = EmployeeNumber::firstOrNew(['oa_contacts_id' => $employee->id]);
        if ($oldEmployeeNumber->id) {
            $oldEmployeeNumber->oa_contacts_id = 0;
            $result = $oldEmployeeNumber->save() && $result;
        }
        $newEmployeeNumber = EmployeeNumber::find($employee_number);
        if (is_null($newEmployeeNumber)) xThrow(ERR_OA_CONTACTS_NOT_EXIST);
        $newEmployeeNumber->oa_contacts_id = $employee->id;
        $result = $newEmployeeNumber->save() && $result;

        //只有在编辑时才会操作下列内容
        if ($id) {

            //绑定角色
            $bindRole = new \App\Http\Admin\AppManage\Models\UserRole();
            $result = $bindRole->roleBind([$user->customer_id], $role_id) && $result;

            if ($employee->type == 1) {
                //如果是正式员工类型，添加到人事档案
                $file = PersonnelFile::firstOrNew(['oa_company_id' => $company_id, 'oa_contacts_id' => $employee->id]);
                $file->fill([
                    'oa_department_id'              => $department_id,
                    'position'                      => $position,
                    'name'                          => $name,
                    'sex'                           => $sex,
                    'ethnicity'                     => $ethnicity ?: '',
                    'birthplace'                    => $birthplace,
                    'education'                     => $education,
                    'birthdate'                     => $birthdate ? strtotime($birthdate) : 0,
                    'credential_type'               => $credential_type,
                    'credential_number'             => $credential_number,
                    'mobile'                        => $mobile,
                    'email'                         => $employee->email,
                    'address'                       => $address,
                    'marital_status'                => $marital_status,
                    'household_registratio_type'    => $household_registratio_type,
                    'personnel_sources'             => $personnel_sources ?: '',
                    'health_certificate_term'       => $health_certificate_term ? strtotime($health_certificate_term) : 0,
                    'profile_photo_url'             => $employee->profile_photo_url,
                    'note'                          => $note ?: '',
                    'accumulation_fund'             => $accumulation_fund ?: 0,
                    'accumulation_fund_base'        => $accumulation_fund_base ?: 0,
                    'accumulation_fund_adjust_time' => $accumulation_fund_adjust_time ? strtotime($accumulation_fund_adjust_time) : 0,
                    'social_security_base'          => $social_security_base ?: 0,
                    'insured_adjust_time'           => $insured_adjust_time ? strtotime($insured_adjust_time) : 0,
                    'status'                        => 1
                ]);
                $result = $file->save() && $result;
                $belong_id = $file->id;
            } elseif ($employee->type == 2) {
                //如果是临时工类型，添加到临时工表
                $worker = TemporaryWorker::firstOrNew(['oa_contacts_id' => $employee->id]);
                $worker->fill([
                    'oa_company_id'     => $employee->oa_company_id,
                    'position'          => $employee->position,
                    'start_time'        => $start_time ? strtotime($start_time) : 0,
                    'name'              => $name,
                    'sex'               => $sex,
                    'birthplace'        => $birthplace,
                    'birthdate'         => $birthdate ? strtotime($birthdate) : 0,
                    'credential_type'   => $credential_type,
                    'credential_number' => $credential_number,
                    'address'           => $address,
                ]);
                $result = $worker->save() && $result;
                $belong_id = $worker->id;
            } else {
                xThrow(ERR_OPTION_NOT_EXIST_IN_DATABASE);
            }

            //如果不存在工作记录，直接新建；如果已存在，并且岗位发生了调动，将原来的工作记录填上结束时间，并新建一条工作记录
//            $oldWorkHistory = WorkHistory::where([['oa_contacts_id', $employee->id], ['end_time', 0]])->first();
//            if (is_null($oldWorkHistory)) {
//                $newWorkHistory = new WorkHistory;
//                $newWorkHistory->fill([
//                    'oa_contacts_id'   => $employee->id,
//                    'oa_company_id'    => $employee->oa_company_id,
//                    'oa_department_id' => $employee->oa_department_id,
//                    'position'         => $employee->position,
//                    'start_time'       => time(),
//                    'belong_type'      => $type,
//                    'belong_id'        => $belong_id
//                ]);
//                $result = $newWorkHistory->save() && $result;
//            } elseif ($oldWorkHistory->oa_company_id != $employee->oa_company_id ||
//                $oldWorkHistory->oa_department_id != $employee->oa_department_id ||
//                $oldWorkHistory->position != $employee->position
//            ) {
//                $oldWorkHistory->end_time = time();
//                $result = $oldWorkHistory->save() && $result;
//                $newWorkHistory = new WorkHistory;
//                $newWorkHistory->fill([
//                    'oa_contacts_id'   => $employee->id,
//                    'oa_company_id'    => $employee->oa_company_id,
//                    'oa_department_id' => $employee->oa_department_id,
//                    'position'         => $employee->position,
//                    'start_time'       => time(),
//                    'belong_type'      => $type,
//                    'belong_id'        => $belong_id
//                ]);
//                $result = $newWorkHistory->save() && $result;
//            }
        }

        if ($result) {
            \DB::commit();
            return true;
        } else {
            \DB::rollBack();
            return false;
        }
    }

    /**
     * 删除通讯录成员
     * @author wenwenbin
     * @param int $id 联系人id
     * @param int $company_id 公司id
     * @param int $status 离职方式
     * @param string $evaluate 评价
     * @return bool
     */
    public function delAddressListMember($id, $company_id, $status, $evaluate)
    {
        \DB::beginTransaction();
        $result = true;
        $contacts = Contacts::find($id);
        if (is_null($contacts)) xThrow(ERR_OA_CONTACTS_NOT_EXIST);
        $type = $contacts->type;
        $companyUser = CompanyUser::where([['oa_company_id', $company_id], ['user_id', $contacts->user_id]])->first();
        if (is_null($companyUser)) xThrow(ERR_OA_COMPANY_USER_NOT_EXIST);
        $userRole = UserRole::where('user_id', $contacts->user_id)->first();
        if (is_null($userRole)) xThrow(ERR_APP_ROLE_NOT_EXIST);

        //删除原来的公司用户
        $result = $companyUser->delete() && $result;

        //判断用户有无其他正在使用的公司
        $otherCompanyUserIsUse = CompanyUser::where([['user_id', $contacts->user_id], ['is_use', 1]])->first();
        if (is_null($otherCompanyUserIsUse)) {
            //判断用户有无其他公司
            $otherCompanyUser = CompanyUser::where('user_id', $contacts->user_id)->first();
            if ($otherCompanyUser) {
                $otherCompanyUser->is_use = 1;
                $result = $otherCompanyUser->save() && $result;
                $userRole->role_id = $otherCompanyUser->role_id;
                $result = $userRole->save() && $result;
            } else {
                //赋予app默认角色
                $defaultRoleId = Role::where('name', 'default_role')->value('id');
                if ($defaultRoleId) {
                    $userRole->role_id = $defaultRoleId;
                    $result = $userRole->save() && $result;
                }
            }
        }

        //删除通讯录人员
        $result = $contacts->delete() && $result;

        //删除人事档案或临时工
        if ($type == 1) {
            $personnelFile = PersonnelFile::where([['oa_contacts_id', $id], ['status', 1]])->first();
            if ($personnelFile) {
                $personnelFile->evaluate = $evaluate;
                $personnelFile->status = $status;
                $result = $personnelFile->save() && $result;
            }
        } elseif ($type == 2) {
            $temporaryWorker = TemporaryWorker::where('oa_contacts_id', $id)->first();
            if ($temporaryWorker) {
                $temporaryWorker->end_time = time();
                $result = $temporaryWorker->save() && $result;
            }
        }
        $employeeNumber = EmployeeNumber::where([['oa_contacts_id', $id], ['oa_company_id', $company_id]])->first();
        $employeeNumber->oa_contacts_id = 0;
        $result = $employeeNumber->save() && $result;

        //将工作历史的结束时间替换成现在的时间
        $workHistory = WorkHistory::where([['oa_contacts_id', $id], ['oa_company_id', $company_id], ['end_time', 0]])->first();
        if ($workHistory) {
            $workHistory->end_time = time();
            $result = $workHistory->save() && $result;
        }

        if ($result) {
            \DB::commit();
            return true;
        } else {
            \DB::rollBack();
            return false;
        }
    }

    public function importEmployee($data)
    {
        global $insertData, $error, $err_count, $success_count;
        $insertData = [];
        $error = [];
        $err_count = 0;
        $success_count = 0;
        $modelTitle = ['序号', '姓名', '手机号', '部门（必须为已存在的部门）', '岗位', '工号', '角色（必须为已存在的角色）', 'email（可选）'];
        if ($data[0] === $modelTitle) {
            unset($data[0]);
            //将数据存入待插入数组
            $departmentList = [];
            $roleList = [];
            $companyId = session('current_operation_company_id');
            if (!$companyId) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
            $department = Department::where('oa_company_id', $companyId)->get(['id', 'name']);
            foreach ($department as $item) {
                $departmentList[$item->name] = $item->id;
            }
            $role = Role::where('oa_company_id', $companyId)->get(['id', 'display_name']);
            foreach ($role as $item) {
                $roleList[$item->display_name] = $item->id;
            }
            while (list($k, $v) = each($data)) {
                try {
                    if (!$v[0]) continue;
                    if ($v[1] === null || mb_strlen($v[1]) > 32) throw new \Exception();
                    if ($v[2] === null || mb_strlen($v[2]) != 11 || !is_numeric($v[2])) throw new \Exception();
                    if ($v[3] === null || mb_strlen($v[3]) > 32 || !array_key_exists((string)$v[3], $departmentList)) throw new \Exception();
                    if ($v[4] === null || mb_strlen($v[4]) > 32) throw new \Exception();
                    if ($v[5] === null || mb_strlen($v[5]) > 11) throw new \Exception();
                    if ($v[6] === null || mb_strlen($v[6]) > 32 || !array_key_exists((string)$v[6], $roleList)) throw new \Exception();
                    $this->batchInsertContacts($companyId, $v[1], $v[2], $departmentList[$v[3]], $v[4], $v[5], $roleList[$v[6]], $v[7]);
                    $success_count++;
                } catch (\Exception $e) {
                    $err_count++;
                    $error[] = $v[0];
                    \Log::info($e);
                    continue;
                }
            }
//            //将待插入数组插入
//            foreach (array_chunk($insertData, 1000) as $v) {
//                EloquentBill::insert($v);
//            }
            return $error;
        } else {
            return xThrow(ERR_HTTP_FILE_UPLOAD_FORMAT);
        }
    }

    public function batchInsertContacts($companyId, $name, $mobile, $departmentId, $position, $employeeNumber, $roleId, $email)
    {
        \DB::beginTransaction();

        $employee = Contacts::firstOrNew(['oa_company_id' => $companyId, 'mobile' => $mobile]);
        if ($employee->id) throw new \Exception();
        $employee->fill([
            'oa_department_id'  => $departmentId,
            'name'              => $name,
            'position'          => $position,
            'email'             => $email ?: '',
            'profile_photo_url' => '/images/global/default_avatar.png',
            'type'              => 1
        ]);

        //查找user表里的用户是否存在，如果不存在，先创建用户，再将user_id添加到通讯录表里
        $user = User::firstOrNew(['customer_name' => $mobile]);
        if (is_null($user->customer_id)) {
            $user->fill([
                'customer_mobile'       => $mobile,
                'customer_pass'         => '123456',
                'customer_zhuceshijian' => time(),
                'customer_avatar'       => '/images/global/default_avatar.png'
//                'username' => $mobile,
//                'nickname' => substr_replace($mobile, '****', 3, 4),
//                'name' => $name,
//                'password' => '123456',
//                'profile_photo_url' => $profile_photo_url ?: '/images/global/default_avatar.png',
//                'credential_type' => $credential_type,
//                'credential_number' => $credential_number,
//                'sex' => $sex,
//                'birthdate' => $birthdate ? strtotime($birthdate) : 0,
//                'email' => $email ?: '',
//                'register_ip' => 0, //todo
//                'status' => 10
            ]);
            if (!$user->save()) {
                \DB::rollBack();
                throw new \Exception();
            }
        }

        //绑定公司用户
        $companyUser = new CompanyUserRepository();
        $otherCompanyUserIsUse = $companyUser->find([['user_id', $user->customer_id], ['is_use', 1]]);
        $companyUser->create([
            'oa_company_id'    => $companyId,
            'oa_department_id' => $departmentId,
            'position'         => $position,
            'role_id'          => $roleId,
            'user_id'          => $user->customer_id,
            'is_use'           => is_null($otherCompanyUserIsUse) ? 1 : 0,
            'type'             => 0
        ]);
        if (is_null($otherCompanyUserIsUse)) {
            //赋予app默认公司角色
            $defaultRoleId = Role::where('name', 'default_company_employee')->value('id');
            if (is_null($defaultRoleId)) xThrow(ERR_APP_ROLE_NOT_EXIST);
            $userRole = UserRole::firstOrNew(['user_id' => $user->customer_id]);
            $userRole->role_id = $defaultRoleId;
            if (!$userRole->save()) {
                \DB::rollBack();
                throw new \Exception();
            }
        }

        //绑定通讯录
        $employee->user_id = $user->customer_id;
        if (!$employee->save()) {
            \DB::rollBack();
            throw new \Exception();
        }

        //查找该联系人是否已占有工号，如果有，先让该工号的联系人清除，再将该联系人和选择的工号绑定
        $newEmployeeNumber = new EmployeeNumber();
        $newEmployeeNumber->fill([
            'oa_company_id'   => $companyId,
            'oa_contacts_id'  => $employee->id,
            'employee_number' => $employeeNumber
        ]);
        if (!$newEmployeeNumber->save()) {
            \DB::rollBack();
            throw new \Exception();
        }

        \DB::commit();
        return true;
    }

    public function getCompanyResumeInfo($oaContactsId)
    {
        $companyResume = new CompanyResumeRepository();
        $resumeInfo = $companyResume->find(['oa_contacts_id' => $oaContactsId]);
        if (is_null($resumeInfo)) xThrow(ERR_OA_COMPANY_RESUME_NOT_EXIST);
        $contactsList = Contacts::has('companyInfo')
            ->with('companyInfo', 'workHistoryList')
            ->where('user_id', $resumeInfo->user_id)
            ->get(['id', 'oa_company_id']);
        foreach ($contactsList as $contacts) {
            $contacts->company = $contacts->companyInfo->name;
            foreach ($contacts->workHistoryList as $k => $workHistory) {
                if ($k == 0) $contacts->start_time = date('Y-m-d', $workHistory->start_time);
                $contacts->end_time = $workHistory->end_time == 0 ? date('Y-m-d', time()) :
                    date('Y-m-d', $workHistory->end_time);
            }
            unset($contacts->companyInfo, $contacts->workHistoryList);
        }

        //获取所有城市数据
//        $cityIds = $workLocationIds = explode(',', $resumeInfo->jobPreferencesInfo->work_location_ids);
//        if (!in_array($resumeInfo->current_city_id, $cityIds))
        $cityIds[] = $resumeInfo->current_city_id;

        $city = new CityRepository();
        $cityList = $city->getListByIds($cityIds);

        $cityMap = [];
        foreach ($cityList as $city) {
            $cityMap[$city->cityID] = [
                'city_id'       => $city->cityID,
                'city_name'     => $city->city,
                'province_id'   => $city->provinceInfo->provinceID,
                'province_name' => $city->provinceInfo->province
            ];
        }

        /**
         * 基本信息处理
         */
        // 姓名
        $resumeInfo->full_name = !empty($resumeInfo->full_name) ? $resumeInfo->full_name : $resumeInfo->first_name . $resumeInfo->last_name;
        // 头像
        $resumeInfo->profile_photo_url = !empty($resumeInfo->profile_photo_url) ? env('APP_URL') . $resumeInfo->profile_photo_url : '';
        // 性别
        switch ($resumeInfo->gender) {
            case 1:
                $resumeInfo->gender_format = '男';
                break;
            case 2:
                $resumeInfo->gender_format = '女';
                break;
            default:
                $resumeInfo->gender_format = '未知';
        }
        // 出生日期
        $resumeInfo->date_of_birth_format = date('Y年m月d日', $resumeInfo->date_of_birth);
        // 开始工作年份
        $resumeInfo->job_start_time_format = !empty($resumeInfo->job_start_time) ? date('Y年m月', $resumeInfo->job_start_time) : '暂无经验';
        // 学历
        switch ($resumeInfo->education) {
            case 1:
                $resumeInfo->education_format = '初中及以下';
                break;
            case 2:
                $resumeInfo->education_format = '高中';
                break;
            case 3:
                $resumeInfo->education_format = '中技';
                break;
            case 4:
                $resumeInfo->education_format = '中专';
                break;
            case 5:
                $resumeInfo->education_format = '大专';
                break;
            case 6:
                $resumeInfo->education_format = '本科';
                break;
            case 7:
                $resumeInfo->education_format = '硕士';
                break;
            case 8:
                $resumeInfo->education_format = '博士';
                break;
            case 9:
                $resumeInfo->education_format = 'MBA';
                break;
            default:
                $resumeInfo->education_format = '未知';
        }
        // 工作状态
        switch ($resumeInfo->job_status) {
            case 1:
                $resumeInfo->job_status_format = '离职';
                break;
            case 2:
                $resumeInfo->job_status_format = '在职';
                break;
            default:
                $resumeInfo->job_status_format = '未知';
        }
        // 证件类型
        switch ($resumeInfo->id_type) {
            case 1:
                $resumeInfo->id_type_format = '身份证';
                break;
            case 2:
                $resumeInfo->id_type_format = '护照';
                break;
            case 3:
                $resumeInfo->id_type_format = '军人证';
                break;
            case 4:
                $resumeInfo->id_type_format = '香港身份证';
                break;
            case 10:
                $resumeInfo->id_type_format = '其它';
                break;
            default:
                $resumeInfo->id_type_format = '未知';
        }
        // 工作经验
        switch ($resumeInfo->work_experience) {
            case 1:
                $resumeInfo->work_experience_format = '1年以下';
                break;
            case 2:
                $resumeInfo->work_experience_format = '1-3年';
                break;
            case 3:
                $resumeInfo->work_experience_format = '3-5年';
                break;
            case 4:
                $resumeInfo->work_experience_format = '5-10年';
                break;
            case 5:
                $resumeInfo->work_experience_format = '10年以上';
                break;
            default:
                $resumeInfo->work_experience_format = '暂无经验';
        }
        // 当前所在地
        $resumeInfo->current_city_info = isset($cityMap[$resumeInfo->current_city_id]) ? $cityMap[$resumeInfo->current_city_id] : new \stdClass();

        unset(
            $resumeInfo->is_default,        //默认简历
            $resumeInfo->publicity,         //公开程序
            $resumeInfo->marital_status,    //婚姻状态
            $resumeInfo->language           //简历语言
        );

        return ['resumeInfo' => $resumeInfo, 'workHistoryList' => $contactsList];
    }

    /**
     * 获取公共模版员工列表数据
     * @author wenwenbin
     * @param int $company_id 公司id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getAddressListEmployeeList($company_id)
    {
        //切换为易管通的项目
//        $departmentList = Department::where([['oa_company_id', $company_id], ['pid', 0]])
//            ->with(['contactsList' => function ($query) {
//                $query->select('id', 'oa_department_id', 'name', 'mobile', 'position', 'email');
//            }, 'subordinateList'])
//            ->get(['id', 'name']);
//
//        foreach ($departmentList as $k => $department) {
//            foreach ($department->subordinateList as $v => $item) {
//                $department->contactsList[] = $this->getDepartmentEmployeeList($item->id);
//            }
//            unset($department->id, $department->subordinateList);
//        }

        $departmentList = \App\Engine\DepartmentEngine::getDepartmentUserList($company_id);

        return ['list' => $departmentList, 'pageSize' => 10000];
    }

    /**
     * 获取公共模版部门列表数据
     * @author wenwenbin
     * @param int $company_id 公司id
     * @return \Illuminate\Support\Collection
     */
    public function getAddressListDepartmentList($company_id)
    {
        $departmentList = Department::where([['oa_company_id', $company_id]])
//            ->with('contactsList')
            ->get(['id', 'name', 'pid']);
        foreach ($departmentList as $department) {
//            $department->department_id = $department->id;
//            unset($department->id);
            $department->isExpand = 0;
        }

        return ['list' => $departmentList, 'pageSize' => 10000];
    }

    public static function getContactsAsAdminUser($request)
    {
        $user = $request->user('admin');
        $contacts = Contacts::find($user->roles[0]->pivot->oa_contacts_id);
        return $contacts;
    }
}